package com.tianji.learning.mq;

import com.tianji.api.dto.trade.OrderBasicDTO;
import com.tianji.common.constants.MqConstants;
import com.tianji.common.utils.CollUtils;
import com.tianji.learning.service.ILearningLessonService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

//添加课表的监听器，交易服务中用户下单完成后，会投递消息到mq，在此处接收消息
//{"orderId":"1673675057831903234","userId":"2","courseIds":["1549025085494521857"],"finishTime":"2023-06-27 20:50:03"}
@Component
@Slf4j
public class LessonChangeListener {


    @Autowired
    private ILearningLessonService learningLessonService;


    // 订阅学生订单支付成功的消息，获取哪个学生购买了哪些课程
    // {"orderId":"1688025816258080769","userId":"129","courseIds":["1549025085494521857"],"finishTime":"2023-08-06 11:14:51"}
    @RabbitListener(
            bindings = @QueueBinding(
                    exchange = @Exchange(name=MqConstants.Exchange.ORDER_EXCHANGE,type =
                    ExchangeTypes.TOPIC),//交换机
                    value = @Queue(value = "learning.lesson.pay.queue",durable = "true"),//队列
                    key = MqConstants.Key.ORDER_PAY_KEY //bindingKey
            )
    )
    public void listenLessonPay(OrderBasicDTO orderBasicDTO){
        //1.参数校验
        if(orderBasicDTO == null || orderBasicDTO.getUserId() == null || CollUtils.isEmpty(orderBasicDTO.getCourseIds())){
            // 数据有有误，无需处理
            log.error("接收到MQ消息有误，订单数据为空");
            return;
        }
        //2. 调用service添加课程到课表
        log.info("监听到用户{}的订单，需要将课程{}添加到课表",orderBasicDTO.getUserId(),orderBasicDTO.getCourseIds());
        learningLessonService.saveLesson(orderBasicDTO);
    }
}
